<?php

$dir = dirname(__FILE__);
$ROOT = 'C:/Servidor/Apache2/htdocs/chat_tcc/';

require_once("FileHandler.php");
require_once("Database.php");

class Update{
	
	private $fh;
	private $user;
	private $db;
	private $data;

	public function __construct($user, $data=null){
		$this->user = $user;
		$this->data = $data;

		$this->fh = new FileHandler($this->user->getRoom()->getPath());
		$this->db = new Database;
	}

	public function get(){
		$sessionId = $this->user->getSession();		

		$query = "SELECT content FROM session_update WHERE session = $sessionId";
		
		$res = $this->db->execute($query);

		$response = '';

		if($this->db->getNumberOfRows() > 0){
			$row = mysql_fetch_array($res,MYSQL_NUM);
			$content = $row[0];

			$params = array('content' => '','last_activity'=>array('NOW()','function'));
			$condition = array('session' => $sessionId);
			
			$this->db->execute($this->db->getUpdateQuery('session_update',$params,$condition));

			//if($content != '')	$response = str_replace("\n",',',$content);		
			//$response = '['.$response.']';
			$content = parseLineBreaks($content);

			$response = '['.$content.']';
		}else{
			$response = json_encode(0);
		}

		echo $response;
	}	

	public function addMessage($data=null){
		if($data != null) $this->data = $data;

		if(is_object($this->data)) $message = $this->data;
		else $message = $this->data['message'];

		$params = $message->getArray();
		$params['user'] = array($params['user'],'string');

		$array = assocArrayToNumArray($params);
		/*$usersLine = json_encode(array(1, $array));
		$logLine = "\"{$message->getId()}\":".json_encode($array);

		$this->addToUsers($usersLine);
		$this->addToFileAsLog($logLine,'message');

		if($message->isReply()) $this->saveReply($message);

		return $message->getId();*/
		
		$this->db->execute($this->db->getInsertQuery('message',$params));

		$messageId = $this->db->getInsertedId();

		$response = array($messageId);

		if($message->isReply()){
			$parentRepliesNumber = $message->getParentRepliesNumber();
			$paramsReply = array('message'=>$messageId,'parent'=>$message->getParent(),'parent_replies_number'=>$parentRepliesNumber);
			$this->db->execute($this->db->getInsertQuery('reply',$paramsReply));
			//REFATORAR
			//$parentRepliesNumber = $this->saveReply($message);

			$response[] = $parentRepliesNumber;
		}

		//$array[0] = $array[0][0]; //hack
		$array = array_merge(array($messageId),$array);
		$update = array(1,$array);

		$update = $this->convertArrayToJson($update);
		$this->saveToUsers($update);		
//file_put_contents('testemsg', json_encode($update));
		return $response;
	}

	private function saveReply($message,$db=null){
		//$children;

		$message = $message->getId();
		$parent = $message->getParent();
		$parentRepliesNumber = $message->getParentRepliesNumber();

		$params = array('message'=>$message,'parent'=>parent,'parent_replies_number'=>$parentRepliesNumber);

		if($db != null) $db = new Database;
		$db->execute($db->getInsertQuery('reply',$paramsReply));

		/*$replyObject = json_decode($this->fh->getFileContent('reply'));

		if(!isset($replyObject->children->$reply)) $children = array($id);
		else{
			$children = $replyObject->children->$reply;
			$children[] = $id;
		}

		$replyObject->children->$reply = $children;
		$replyObject->parent->$id = $reply; //adiciona o reply como pai da mensagem

		$this->fh->createFile('reply',json_encode($replyObject));*/
		return $parentRepliesNumber;
	}

	public function addAccess($data=null){
		if($data != null) $this->data = $data;
		//$array = $this->getAccessArray($this->data['access']);
		//data for update
		$params['type'] = $this->data['access'];
		$params['user'] = $this->user->getId();
		$params['time'] = date('Y-m-d H:i:s');

		$array = assocArrayToNumArray($params);	
		$update = array(2,$array);

		$params['user'] = array($params['user'],'string');
		$params['room'] = $this->user->getRoom()->getId();
		$this->db->execute($this->db->getInsertQuery('access',$params));

		/*$usersLine = json_encode(array(2, $array));
		$logLine = json_encode($array);
		
		$this->addToUsers($usersLine);
		$this->addToFileAsLog($logLine,'login');*/
		$this->saveToUsers($update);
	}

	public function addStatus($data=null){
		if($data != null) $this->data = $data;
		
		//$array = $this->getStatusArray($this->data['status']);
		//$usersLine = json_encode(array(3, $array));

		//$this->addToUsers($usersLine);
		//data for update
		$type = $this->data['status'];
		$params['type'] = $type;
		$params['user'] = $this->user->getId();
	
		$array = assocArrayToNumArray($params);
		$update = array(3,$array);

		$params['user'] = array($params['user'],'string');
		$params['room'] = $this->user->getRoom()->getId();
		$this->db->execute($this->db->getInsertQuery('status',$params));

		$session = $this->user->getSession();
		$params = array('session'=>$session,'status'=>$type);	
		$this->db->execute($this->db->getUpdateQuery('session_update',$params,array('session'=>$session)));

		$this->saveToUsers($update);
	}
	/*
	private function getStatusArray($status){
		return array($this->user->getId(), date('d/m/Y h:i:s'), $status);
	}

	private function getAccessArray($access){
		return array($this->user->getId(), date('d/m/Y h:i:s'), $access);
	}

	public function addToUsers($line){
		$this->fh->appendToFiles($line,'user/',array(''.$this->user->getId() => true));
	}

	public function addToFileAsLog($line,$file){
		$this->fh->appendToFiles($line,$file);
	}*/

	public function saveToUsers($update){
		//if(!is_string($update)) $update = json_encode($update);
		if(!is_string($update)) $update = $this->convertArrayToJson($update);
		
		$meId = $this->user->getId();

		$roomId = $this->user->getRoom()->getId();
		
//		$query = "UPDATE session_update SET content = CONCAT(content, '$update','\n') WHERE room = $roomId AND user <> '$meId'";
		$query = "UPDATE session_update SET content = ( CASE WHEN content = '' THEN '$update' ELSE CONCAT(content, ',','$update') END ) WHERE room = $roomId AND user <> '$meId' ";

		$this->db->execute($query);
		/*foreach($members as $member){
			$userId = $member['id'];
			if($userId != $meId){
				$query = "UPDATE session_update SET content = CONCAT(content, '$update') AND last_activity = NOW() WHERE user = '$userId'";
				$this->db->execute($query);
			}
		}*/
	}

	private function convertArrayToJson($array){
		$value = null;
		$arrayJson = array();

		for($i = 0, $len = count($array); $i < $len; $i++){
			$value = $array[$i];

			if(is_array($value)){
				 if($value[1] == 'string') $value = '"'.$value[0].'"';
				 else $value = $this->convertArrayToJson($value);	
			} 
			else{
				if($value === null) $value = 'null';
				else if(!is_numeric($value)) $value = '"'.$value.'"';
			}
			
			array_push($arrayJson, $value);
		}

		return '['.implode(',', $arrayJson).']';
	}	

}

function parseLineBreaks($text) {
    $text = str_replace("\r\n", "\n", $text);
    $text = str_replace("\r", "\n", $text);

    $text = str_replace("\n", "\\n", $text);
    return $text;
}

?>